//
//  UITextField+inputAccessory.m
//  PPDL
//
//  Created by 王洋 on 2019/8/7.
//  Copyright © 2019 王洋. All rights reserved.
//

#import <objc/runtime.h>
#import "UITextField+inputAccessory.h"

@implementation UITextField (inputAccessory)

- (UIView *)inputAccessoryView{
    if (self.isHiddenCustomAccessoryView) {
        return [[UIView alloc]init];
    }
    if (self.customAccessoryView) {
        return self.customAccessoryView;
    }
    return [self creatCustomAccessoryView];
}

#pragma mark - event response
- (void)resignKeyBoardResponse{
    [self endEditing:YES];
}
#pragma mark - private method
- (UIView *)creatCustomAccessoryView{
    
    UIToolbar * toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
    
    UIBarButtonItem * space1 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem * space2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem * doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"隐藏键盘" style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyBoardResponse)];
    
    [toolBar setItems:@[space1, space2, doneBtn]];
    return toolBar;
}

#pragma mark - setters && getters
- (void)setCustomAccessoryView:(UIView *)customAccessoryView{
    objc_setAssociatedObject(self, @selector(customAccessoryView), customAccessoryView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIView *)customAccessoryView{
    //_cmd 表示当前方法的selector
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setIsHiddenCustomAccessoryView:(BOOL)isHiddenCustomAccessoryView{
    objc_setAssociatedObject(self, @selector(isHiddenCustomAccessoryView), @(isHiddenCustomAccessoryView), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)isHiddenCustomAccessoryView{
    NSNumber * num = objc_getAssociatedObject(self, _cmd);
    return (num && [num isKindOfClass:NSNumber.self]) ? [num boolValue] : NO;
}

@end
